'use client';

import { useToast } from '@/hooks/use-toast';
import trpc from '@/lib/trpc/client';
import { queryClient } from '@/providers/trpc-provider';
import { shopInfoSchema } from '@/service/actions/schema/shop';
import { updateShopInfo } from '@/service/actions/shop';
import type { ShopType } from '@/service/type/shop';
import { zodResolver } from '@hookform/resolvers/zod';
import { getQueryKey } from '@trpc/react-query';
import { useState } from 'react';
import { useTransition } from 'react';
import { useForm } from 'react-hook-form';
import type { z } from 'zod';
import { PoiSearchFormItem } from '../common/poi-search-form-item';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '../ui/form';
import { Input } from '../ui/input';

const ShopForm = ({
  preData,
  setOpen,
}: {
  preData: ShopType;
  setOpen: React.Dispatch<React.SetStateAction<boolean>>;
}) => {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const form = useForm<z.infer<typeof shopInfoSchema>>({
    resolver: zodResolver(shopInfoSchema),
    defaultValues: {
      name: preData.name,
      address: {
        address: preData.address,
        longitude: preData.longitude,
        latitude: preData.latitude,
      },
      contactPhone: preData.contactPhone,
      description: preData.description ?? '',
      deliveryMinPrice: preData.deliveryMinPrice,
      startTime: preData.startTime,
      endTime: preData.endTime,
    },
  });

  const onSubmit = async (data: z.infer<typeof shopInfoSchema>) => {
    if (!data.address)
      return toast({ title: '请选择地址', variant: 'destructive' });
    startTransition(async () => {
      const { error } = await updateShopInfo(data);
      error
        ? toast({
            variant: 'destructive',
            title: error.message,
          })
        : toast({
            title: '更新成功',
          });
      !error &&
        queryClient.invalidateQueries({
          queryKey: getQueryKey(trpc.shop.getShop),
        });
      !error && setOpen(false);
    });
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-5">
        <div className="grid grid-cols-2 gap-7">
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>商铺名称</FormLabel>
                <FormControl>
                  <Input placeholder="商铺名称" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <PoiSearchFormItem<typeof shopInfoSchema>
            label="商铺地址"
            name="address"
            control={form.control}
          />
          <FormField
            control={form.control}
            name="contactPhone"
            render={({ field }) => (
              <FormItem>
                <FormLabel>联系电话</FormLabel>
                <FormControl>
                  <Input placeholder="联系电话" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="description"
            render={({ field }) => (
              <FormItem>
                <FormLabel>商铺简介</FormLabel>
                <FormControl>
                  <Input placeholder="商铺简介" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="deliveryMinPrice"
            render={({ field }) => (
              <FormItem>
                <FormLabel>起送价</FormLabel>
                <FormControl>
                  <Input placeholder="起送价" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="startTime"
            render={({ field }) => (
              <FormItem>
                <FormLabel>开始营业时间</FormLabel>
                <FormControl>
                  <Input type="time" placeholder="开始营业时间" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="endTime"
            render={({ field }) => (
              <FormItem>
                <FormLabel>结束营业时间</FormLabel>
                <FormControl>
                  <Input type="time" placeholder="结束营业时间" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>
        <div className="flex justify-between">
          <Button
            variant="outline"
            type="button"
            onClick={() => {
              setOpen(false);
              form.reset();
            }}
          >
            取消
          </Button>
          <Button disabled={isPending} type="submit">
            {isPending && <span className="i-ri-loader-4-line animate-spin" />}
            保存
          </Button>
        </div>
      </form>
    </Form>
  );
};

export default function EditShopInfo({ preData }: { preData: ShopType }) {
  const [open, setOpen] = useState(false);

  return (
    <Dialog open={open}>
      <DialogTrigger asChild onClick={() => setOpen(true)}>
        <Button>编辑</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>编辑商铺信息</DialogTitle>
          <DialogDescription className="hidden" />
        </DialogHeader>
        <ShopForm preData={preData} setOpen={setOpen} />
      </DialogContent>
    </Dialog>
  );
}
